<template>
  <div class="box-yuyi">
    <div class="box-left">
      <avue-tree :option="treeOption"
                 :data="treeData"
                 ref="tree"
                 @save="handleSave"
                 @update="handleUpdate"
                 @node-click="nodeClick">
        <div class="custom-tree-node show-hide" slot-scope="scope">
          <span onselectstart="return false">{{ scope.data.dictName }}</span>
          <span class="tree-btn">
            <el-button
              type="text"
              size="small"
              class="btn"
              @click.stop="handleRowEditTree(scope)">
              <i class="el-icon-edit"></i>
            </el-button>
            <el-button
              type="text"
              size="small"
              class="btn"
              @click.stop="removeNode(scope.data.id)">
              <i style="color: #F56C6C" class="el-icon-delete"></i>
            </el-button>
          </span>
        </div>
      </avue-tree>
    </div>
    <section class="box-content">
      <hgroup class="title">字典详情【{{title}}】</hgroup>

      <div class="head-search">
        <search @onSubmit="onSearch">
          <el-form-item label="字典标签">
            <el-input placeholder="请输入内容" clearable v-model="searchData.dictLabel" size="small"></el-input>
          </el-form-item>
        </search>
        <el-button class="reset" size="small" icon="el-icon-refresh" @click="handleReset">重置</el-button>
      </div>
      <div class="fun-btn">
        <el-button size="small"
                   type="primary"
                   @click="handleAddEdit"
                   icon="el-icon-circle-plus-outline">新增
        </el-button>
        <el-button size="small" type="danger" @click="handleDel" plain icon="el-icon-delete">删除</el-button>
      </div>

      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="tableData"
                 :page.sync="page"
                 ref="crud"
                 @current-change="handleCurrentChange"
                 @size-change="handleSizeChange"
                 @selection-change="selectionChange"
                 @row-save="handleRowSave"
                 @row-update="handleRowUpdate"
      >
        <template slot-scope="{row}" slot="icon">
          <i :class="row.icon" style="font-size: 20px"/>
        </template>
        <template slot="isKeep" slot-scope="{row}">
          <el-switch v-model="row.isKeep" @change="handleRowUpdate(row)"></el-switch>
        </template>
        <template slot="isEnable" slot-scope="{row}">
          <el-switch v-model="row.isEnable" @change="handleRowUpdate(row)"></el-switch>
        </template>
      </avue-crud>
    </section>
  </div>
</template>

<script>
import Search from '../../../../../components/search/search'
import {
  addArchivesDic,
  addArchivesDicDetList,
  addSysDic,
  addSysDicDetList,
  delArchivesDic,
  delArchivesDicDetList,
  delSysDic,
  delSysDicDetList,
  editArchivesDic,
  editArchivesDicDetList,
  editSysDic,
  editSysDicDetList,
  getArchivesDic,
  getArchivesDicDetList,
  getSysDic,
  getSysDicDetList
} from '../../../../../api/dictionary/dictionary'

export default {
  name: 'dictionaryItem',
  props: {
    menuType: {
      type: String,
      default: () => 'sys'
    }
  },
  components: { Search },
  // 菜单设置（下级菜单）
  data () {
    return {
      treeData: [],
      treeOption: {
        accordion: true, // 只展开一层
        menu: false,
        formOption: {
          labelWidth: 100,
          column: [{
            label: '字典名称',
            prop: 'dictName',
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入字典名称',
                trigger: 'blur'
              }
            ]
          }, {
            label: '字典类型名',
            prop: 'dictTypeName',
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入字典类型名',
                trigger: 'blur'
              }
            ]
          }, {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            span: 24,
            minRows: 4,
            maxlength: 200,
            showWordLimit: true
          }]
        },
        props: {
          labelText: '标题',
          label: 'dictName',
          value: 'id',
          children: 'children'
        }
      },
      pid: 0,
      title: '',
      searchData: {
        dictLabel: '',
        dictTypeName: ''
      },
      tableSelected: [],
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        pageSizes: [20, 40, 60, 80],
        total: 0
      },
      tableData: [],
      option: {
        align: 'center',
        menuAlign: 'center',
        header: false,
        border: true,
        size: 'medium',
        height: 'calc(100vh - 335px)',
        index: true, // 显示序号
        indexLabel: '序号', // 显示序号
        selection: true, // 多选
        // editBtn: false, // 行内编辑按钮
        delBtn: false, // 行内删除按钮
        viewBtn: true, // 行内查看按钮
        menuWidth: 200,
        column: [
          {
            label: '字典标签',
            prop: 'dictLabel',
            rules: [
              {
                required: true,
                message: '请输入字典标签',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '字典键值',
            prop: 'dictValue',
            rules: [
              {
                required: true,
                message: '请输入字典键值',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '可用',
            prop: 'isEnable',
            type: 'switch',
            value: true,
            slot: true
          },
          {
            label: '排序号',
            prop: 'orderNo',
            type: 'number',
            sortable: true,
            rules: [
              {
                required: true,
                message: '请输入排序号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '图标样式',
            type: 'select',
            prop: 'iconCss',
            span: 12,
            dicData: [
              {
                label: '红',
                value: 'dict_red'
              }, {
                label: '橙',
                value: 'dict_orange'
              }, {
                label: '绿',
                value: 'dict_green'
              }, {
                label: '蓝',
                value: 'dict_blue'
              }, {
                label: '粉',
                value: 'dict_pink'
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            minRows: 4,
            span: 24,
            maxlength: 200,
            showWordLimit: true,
            hide: true
          }
        ]
      }
    }
  },
  mounted () {
    this.getTreeList()
  },
  methods: {
    getTreeList () {
      const param = {
        pageNo: 1,
        pageSize: 1000
      }
      const getData = this.menuType === 'sys' ? getSysDic(param) : getArchivesDic(param)
      getData.then(res => {
        this.treeData = res.data.data.list
      })
    },
    handleSave (parent, data, done, loading) {
      console.log(parent)
      // 新增字典列表
      const addData = this.menuType === 'sys' ? addSysDic(data) : addArchivesDic(data)
      addData.then(() => {
        this.getTreeList()
        done()
      }).catch(() => {
        loading()
      })
    },
    handleRowEditTree (data) {
      // 修改树节点
      this.$refs.tree.nodeContextmenu('t', data.data)
      this.$refs.tree.rowEdit()
    },
    handleUpdate (parent, data, done, loading) {
      console.log(parent)
      // 修改字典列表
      const updateData = this.menuType === 'sys' ? editSysDic(data) : editArchivesDic(data)
      updateData.then(() => {
        this.getTreeList()
        done()
      }).catch(() => {
        loading()
      })
    },
    removeNode (id) {
      // 移除节点
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = [id]
        const delData = this.menuType === 'sys' ? delSysDic(ids) : delArchivesDic(ids)
        delData.then(res => {
          this.loading = true
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getTreeList()
          this.onLoad()
        })
      }).catch(() => {
      })
    },
    onLoad () {
      // 加载列表
      this.loading = true
      const query = {
        pageSize: this.page.pageSize,
        pageNo: this.page.currentPage
      }
      const params = []
      Object.keys(this.searchData).forEach((key) => {
        if (this.searchData[key]) {
          params.push({
            op: key === 'dictTypeName' ? 'eq' : 'like',
            name: key,
            value: this.searchData[key]
          })
        }
      })
      if (params.length > 0) {
        query.params = params
      } else {
        delete query.params
      }
      const getDetList = this.menuType === 'sys' ? getSysDicDetList(query) : getArchivesDicDetList(query)
      getDetList.then(res => {
        this.tableData = res.data.data.list
        this.page.total = res.data.data.total
        this.loading = false
      })
    },
    handleCurrentChange (currentPage) {
      // 翻页 第几页
      this.page.currentPage = currentPage
    },
    handleSizeChange (pageSize) {
      // 翻页 一页多少条
      this.page.pageSize = pageSize
    },
    handleReset () {
      // 重置
      this.searchData.dictLabel = ''
    },
    onSearch () {
      // 搜索
      if (this.searchData.dictTypeName) {
        this.page.currentPage = 1
        this.page.pageSize = 20
        this.onLoad()
      } else {
        this.$message.warning('请选择左侧数据字典进行查询！')
      }
    },
    handleAddEdit () {
      // 打开新增窗口
      if (this.searchData.dictTypeName) {
        this.$refs.crud.rowAdd()
      } else {
        this.$message.warning('请选择左侧数据字典进行新增！')
      }
    },
    handleRowSave (row, done, loading) {
      // 保存新增表格
      row.dictTypeName = this.searchData.dictTypeName
      const addData = this.menuType === 'sys' ? addSysDicDetList(row) : addArchivesDicDetList(row)
      addData.then(() => {
        this.getTreeList()
        this.onLoad()
        this.$message({
          type: 'success',
          message: '操作成功!'
        })
        done()
      }).catch(() => {
        loading()
      })
    },
    handleRowUpdate (row, index, done, loading) {
      // 编辑修改表格
      const editData = this.menuType === 'sys' ? editSysDicDetList(row) : editArchivesDicDetList(row)
      editData.then(() => {
        this.onLoad()
        this.$message({
          type: 'success',
          message: '操作成功!'
        })
        done()
      }).catch(() => {
        loading()
      })
    },
    selectionChange (val) {
      // 选择表格
      this.tableSelected = val
    },
    handleDel () {
      if (this.tableSelected.length < 1) {
        this.$message.warning('请至少勾选一条需要删除的菜单信息！')
      } else {
        this.$confirm('此操作将永久删除选中的信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const ids = []
          this.tableSelected.map((item) => {
            ids.push(item.id)
          })
          const delListData = this.menuType === 'sys' ? delSysDicDetList(ids) : delArchivesDicDetList(ids)
          delListData.then(res => {
            this.loading = true
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.onLoad()
          })
        }).catch(() => {
        })
      }
    },

    nodeClick (data) {
      // 选择tree节点
      this.searchData.dictTypeName = data.dictTypeName
      this.title = data.dictName
      this.onLoad()
    }
  }
}
</script>

<style lang="scss" scoped>
  .box-yuyi {

    .box-left, .box-content {
      height: calc(100vh - 155px);
    }

    .box-left {
      ::v-deep .avue-tree {
        height: calc(100% - 5px);
      }

      ::v-deep .el-tree-node__content {
        &:hover {
          .tree-btn {
            display: inline-block;
          }
        }
      }

      .tree-btn {
        margin-left: 20px;
        display: none;

        .btn:hover {
          opacity: 0.8;
        }
      }
    }

    .box-content {
      hgroup.title {
        color: #000;
        padding: 5px 0 10px 0;
      }

      ::v-deep .search-btn {
        margin-top: 0px;
      }

      .reset {
        margin-top: 5px;
      }
    }
  }
</style>
